package atguigu.thread.task;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Demo2 {

    public static void main(String[] args) {
        // 这里启动一个异步任务
        CompletableFuture<Client> future = Client.connect();
        System.out.println("主线程继续。。。");

        future.thenApply(c->{
            System.out.println("异步任务进行计算");
            try {
                Thread.sleep(1000*2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String s = c.sendMsg();
           System.out.println(s);
           return c;
       });

        // 这里始终会执行，超时了也会执行
        future.whenCompleteAsync((c,e)->{
            System.out.println("完成了");
        });

        try{
            System.out.println("等待结果");
            Client client = future.get(3, TimeUnit.SECONDS);
            System.out.println("获取结果");


        }catch (Exception e){
            future.completeExceptionally(e);
            e.printStackTrace();
        }
    }
}
